package com.ufo.store.management;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.multidex.MultiDex;

import com.bumptech.glide.Glide;
import com.bumptech.glide.integration.okhttp.OkHttpUrlLoader;
import com.bumptech.glide.load.model.GlideUrl;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.squareup.okhttp.OkHttpClient;
import com.ufo.store.management.net.UnsafeOkHttpClient;
import com.ufo.store.management.utils.CrashHandler;
import com.videogo.constant.Config;
import com.videogo.openapi.EZOpenSDK;
import com.yanzhenjie.nohttp.InitializationConfig;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.URLConnectionNetworkExecutor;
import com.yanzhenjie.nohttp.cache.DBCacheStore;
import com.yanzhenjie.nohttp.cookie.DBCookieStore;

public class BarApplication extends Application {
    //萤石云
    public static String API_URL = "https://open.ys7.com";
    public static String WEB_URL = "https://auth.ys7.com";
    public static String YSVIDEO_APP_KEY = "c42aff23b3ed45378e21e9e55d7333d8";
    public static String YSVIDEO_APP_SECRET = "e436e02a549d2ab4926aebc99eae48f3";

    //qiniu存储
    public static String Qiniu_AccessKey = "YTeN4v_-RBMkJr9xdpRHs_jkSsyoq1X8ho5TjNZr";
    public static String Qiniu_SecretKey = "t-Xs6ONde4XcYDQk3VZktCX0FoEptcDFxb9hRrg2";
    public static String Qiniu_Bucket = "tory198603252415";
    public static String Qiniu_BaseDownloadHost = "http://pv4tuta8m.bkt.clouddn.com/";

    //视频通信
    public static int udp_maxpacket_size = 1400;
    public static int rtp_header_len = 12;
    public static int remote_port_video = 50000;
    public static int remote_port_audio = 50002;
    public static InetAddress remote_address = null;

    //下载
    public static final String mSaveDirPath = Environment.getExternalStorageDirectory() + "/store";
    public static final String mSaveLogoDirPath = Environment.getExternalStorageDirectory() + "/store/logo/";
    public static final String mSaveAPKDirPath = Environment.getExternalStorageDirectory() + "/store/apk/";
    public static final String mSaveCrashDirPath = Environment.getExternalStorageDirectory() + "/store/crash/";
    public static final String mSavePictureDirPath = Environment.getExternalStorageDirectory() + "/store/pictures/";
    public static String mSaveLogoFile = null;
    public static String mSaveAPkFile = null;
    public static String apptoken = "";

    //商品列表显示设置
    public static String downloadBaseUri;
    public static String mStoreName;
    public static boolean mbStockDisplayCost;
    public static boolean mbStockDisplayPicture;
    public static boolean mbStockDisplayInnerCircle;
    public static int mStatisticsStockNumber;
    public static boolean mDatabaseIsSqlServer;
    public static String mSqlServerHost;
    public static String mSqlServerUser;
    public static String mSqlServerPassword;
    public static String mSqlServerDatabaseName;

    public static String mSynchronousSourceSaleDate;

    //列表分页显示设置
    public static int pagesize = 20;

    private static BarApplication sApplication = null;
    private SharedPreferences mSettings = null;

    @Override
    public void onCreate() {
        super.onCreate();
        sApplication = this;

        //初始化设置信息
        initData();

        // 初始化崩溃日志记录功能
        initCrashHandler();

        // 初始化Gilide图片加载
        initGlide();

        //初始化网络环境
        initNoHttp();

        //萤石云开平台初始化
        initEZOpenSDK();

        //初始化科大讯飞语音合成
        initSpeech();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static synchronized BarApplication getInstance() {
        if (sApplication == null)
            sApplication = new BarApplication();
        return sApplication;
    }

    /**
     * 初始化设置信息
     */
    private void initData(){
        try {
            remote_address = InetAddress.getByName("224.0.0.1");
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        }

        //拷贝某天的营业记录到本地，用于数据展示,默认当天
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        mSynchronousSourceSaleDate = sdf.format(new Date());

        mSettings = PreferenceManager.getDefaultSharedPreferences(this);
        downloadBaseUri = mSettings.getString("base_url", "http://192.168.1.100:8080");
        mStoreName = mSettings.getString("store_name", "pp");
        mbStockDisplayCost = mSettings.getBoolean("display_cost", true);
        mbStockDisplayPicture = mSettings.getBoolean("display_picture", true);
        mbStockDisplayInnerCircle = mSettings.getBoolean("display_inner_circle", true);
        mStatisticsStockNumber = mSettings.getInt("statistics_stock_number", 10);
        mDatabaseIsSqlServer = mSettings.getBoolean("database_sqlserver", true);
        mSqlServerHost = mSettings.getString("sqlserver_host", "106.12.122.66:33433");//106.12.122.66
        mSqlServerUser = mSettings.getString("sqlserver_user", "sa");
        mSqlServerPassword = mSettings.getString("sqlserver_password", "Cssiss$2018");//Cssiss$2018
        mSqlServerDatabaseName = mSettings.getString("sqlserver_databasename", "isszmbalv8pptg");
    }

    /**
     * 初始化奔溃日志
     */
    private void initCrashHandler(){
        CrashHandler catchHandler = CrashHandler.getInstance();
        catchHandler.init(getApplicationContext());
    }

    /**
     * Glide忽略证书，加载Https图片
     */
    private void initGlide(){
        OkHttpClient client = UnsafeOkHttpClient.getUnsafeOkHttpClient();
        Glide.get(this).getRegistry().replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client));
    }

    /**
     * @desc 网络框架
     * @author taoli
     * @time 2017/4/13 0013
     */
    private void initNoHttp(){
        InitializationConfig config = InitializationConfig.newBuilder(this)
                // 全局连接服务器超时时间，单位毫秒，默认10s。
                .connectionTimeout(8 * 1000)
                // 全局等待服务器响应超时时间，单位毫秒，默认10s。
                .readTimeout(8 * 1000)
                // 配置缓存，默认保存数据库DBCacheStore，保存到SD卡使用DiskCacheStore。
                .cacheStore(
                        // 如果不使用缓存，setEnable(false)禁用。
                        new DBCacheStore(this).setEnable(true)
                )
                // 配置Cookie，默认保存数据库DBCookieStore，开发者可以自己实现CookieStore接口。
                .cookieStore(
                        // 如果不维护cookie，setEnable(false)禁用。
                        new DBCookieStore(this).setEnable(true)
                )
                // 配置网络层，默认URLConnectionNetworkExecutor，如果想用OkHttp：OkHttpNetworkExecutor。
                .networkExecutor(new URLConnectionNetworkExecutor())
                .build();
        NoHttp.initialize(config);
    }

    /**
     * @desc 海康莹石云监控
     * @author taoli
     * @time 2017/4/13 0013
     */
    private void initEZOpenSDK(){
        Config.LOGGING = true;
        EZOpenSDK.initLib(BarApplication.getInstance(), BarApplication.getInstance().YSVIDEO_APP_KEY, "");
    }

    /**
     * @desc 初始化科大讯飞语音合成
     * @author taoli
     * @time 2017/4/13 0013
     */
    private void initSpeech(){
        SpeechUtility.createUtility(BarApplication.this, SpeechConstant.APPID + "=" + "5742c336");
    }
}